package com.yeyi.YTool;


import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.jsoup.nodes.Element;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.*;


public class WikiDownload {

    // 替换 <> 的正则
    private static final String REGEX_XML = "\\<.[^<>]*\\>";

    // 输出文件的分隔符
    private static final String GAP = "\t";

    private void printSub(Element element, long level){
        for(Element e: element.getAllElements()){
            if(level<8){
                this.printSub(e, level+1);
            }
            System.out.println(e);
        }
    }

    public Map<String, String> readFile(String path) {
        // 按插入的顺序
        Map<String, String> map = new LinkedHashMap<>();

        try {
            FileInputStream fis = new FileInputStream(path);
            // 防止路径乱码   如果utf-8 乱码  改GBK     eclipse里创建的txt  用UTF-8，在电脑上自己创建的txt  用GBK
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            int i = 0;
            while ((line = br.readLine()) != null) {
                if(StringUtils.isBlank(line)){
                    continue;
                }
                map.put(line.trim(), line);
                i++;
            }
            br.close();
            isr.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    public boolean deal(){
        File in = new File(".\\src\\main\\resources\\01.广新APP移动端REST接口 - gacne - Confluence.html");

        Document doc = null;
        try {
            doc = Jsoup.parse(in, "UTF-8", "");
        } catch (IOException e) {
            e.printStackTrace();
        }
//        System.out.println(doc.toString());

        Map<String, String> map = this.readFile(".\\src\\main\\resources\\wiki.txt");

        // 01.广新APP移动端REST接口 结点
        Element element = doc.getElementById("childrenspan1900560-0");
        // 子结点
        Elements parents = element.parents();
        for(Element e: parents.get(1).getAllElements().get(0).select("a[href]")){
//            System.out.println(e.toString());
            for(Node n: e.childNodes()){
                String nStr = n.toString();
                if(null!=n && StringUtils.isNotBlank(nStr)){
                    System.out.println(nStr);
                    String s = map.get(nStr.trim());
                    if(null!=s){
                        if("06.用户提交订单信息获取".equals(nStr.trim())
                        || "用户提交订单信息获取".equals(nStr.trim())){
                            System.out.println();
                        }
                        String href = e.attr("href");
                        // 找标题
                        String portNameAndUrl = this.findNameAndUrl(href);

                        int num = this.strAppearNum(s, GAP);
                        // 补足 3 个 分隔符
                        String strTab = this.strRepear(GAP, 3-num>0 ? 3-num : 1);
                        map.put(nStr.trim(),s+strTab+portNameAndUrl+GAP+href);
                        System.out.println(map.get(nStr.trim()));
                    }
                    break;
                }
            }
        }

        return this.writeFile(map);
    }

    /**
     * 返回 sub 在 src 中出现的次数
     * @author yeyi
     * @date 2019/8/20 10:58
     **/
    private int strAppearNum(String src, String sub){
        if(StringUtils.isEmpty(src)||StringUtils.isEmpty(sub)){
            return 0;
        }

        int count = 0;
        while(src.indexOf(sub)>=0) {
            src=src.substring(src.indexOf(sub)+sub.length());
            count++;
        }
        return count;
    }

    /**
     * s 重复 num 次并返回
     * @param s
     * @param num
     */
    private String strRepear(String s, int num){
        StringBuilder sb = new StringBuilder();
        int i=0;
        for(;i<num; i++){
            sb.append(s);
        }
        return sb.toString();
    }

    private boolean writeFile(Map<String, String> map){
        try{
            FileWriter fw=new FileWriter(new File("wikiPort.txt"));
            //写入中文字符时会出现乱码
            BufferedWriter  bw=new BufferedWriter(fw);
            //BufferedWriter  bw=new BufferedWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("E:/phsftp/evdokey/evdokey_201103221556.txt")), "UTF-8")));

            for(Map.Entry<String, String> entries : map.entrySet()){
                bw.write(entries.getValue()+"\r\n");
            }
            bw.close();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 从网页中找到接口名及接口 url,用 GAP 分隔
     * @author yeyi
     * @date 2019/8/19 20:04
     **/
    private String findNameAndUrl(String url){
        Document doc = null;
        try{
            doc = Jsoup.connect(url).header("Cookie", "sidebar_collapsed=false; seraph.confluence=1736709%3A8a0c9bb87658f07c6def3480ab9298a7b78d329a; PHPSESSID=o5fu47enloacv5jpf1jvial5a7; JSESSIONID=160AAE2BD81398C71B2C57808413D517")
                    .get();
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }

        return this.findUrl(doc);
//        Elements nolinks = doc.getElementsByClass("nolink");
//        if(CollectionUtils.isEmpty(nolinks)){
//            return this.findUrl(doc);
//        }
//        String strNolink = nolinks.get(0).toString().replaceAll(REGEX_XML,"");
//        return strNolink;
    }

    /**
     * 当 nolink 找不到时，找内容为“接口路径-SIT”最近的一个pre标签
     * @author yeyi
     * @date 2019/8/20 10:10
     **/
    private String findUrl(Document doc){
        Elements confluenceTds = doc.getElementsByClass("confluenceTd");
        boolean found = false;
        for(Element e: confluenceTds){
            String txt = e.toString().replaceAll(REGEX_XML, "");
            if(found && StringUtils.isNotBlank(txt)){ // 找到“接口路径-SIT”的下一个 confluenceTd
                return txt;
            }
            if("接口路径-SIT".equals(txt.trim())){
//                System.out.println(e.toString());
                found = true;
                continue;
            }
        }

        return "";
    }

    public static void main(String[] args) {
        WikiDownload wd = new WikiDownload();
        wd.deal();
    }
}
